/*
   Copyright 2011-2012 gtalent2@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package main

import (
	"../models"
	eutil "../util"
	"../world"
	"flag"
	"fmt"
	"github.com/gtalent/starfish/gfx"
	"github.com/gtalent/starfish/input"
	"log"
	"os"
	"runtime"
	"runtime/pprof"
)

func main() {
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
	gameDir := flag.String("gameDir", ".", "path to game data")
	flag.Parse()

	os.Chdir(*gameDir)
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	var settings settings
	settings.read("settings.xml")
	writeDemo()

	var lw models.World

	if eutil.LoadObj("world1"+ext, &lw) != nil {
		fmt.Println("Could not load world")
		return
	}

	world.SetTileSize(70, 70)
	w := world.LoadWorld(lw)
	gfx.OpenDisplay(settings.ScreenSettings.Width, settings.ScreenSettings.Height, settings.ScreenSettings.Fullscreen)
	gfx.SetDisplayTitle("Wombat")
	input.Init()

	ls := buildUser()
	user := world.LoadUser(&ls)
	user.UpKey = input.Key_t
	user.DownKey = input.Key_h
	user.RightKey = input.Key_n
	user.LeftKey = input.Key_d
	w.GetZone("zone1"+ext).AddUser(user, "User", 1, 1, 0)

	camera := world.NewCamera(w)
	camera.Set(0, 0, gfx.DisplayWidth(), gfx.DisplayHeight())
	camera.SetFocusSprite(user)
	gfx.AddDrawer(camera)

	input.AddQuitFunc(func() {
		gfx.CloseDisplay()
	})
	input.AddKeyPressFunc(func(e input.KeyEvent) {
		if e.Key == input.Key_Escape {
			gfx.CloseDisplay()
		}
	})
	runtime.GC()
	gfx.Main()
}
